<template>
  <div class="map-page">
    <div class="head">
      <div v-if="loading" class="loading">
        <van-loading color="#ee0a24" type="spinner" />
      </div>
      <div class="search-box">
        <van-search
          v-model="search_key"
          clearable
          show-action
          placeholder="请输入搜索关键词"
          @search="placeSearchDebounce"
          @input="onKeyInputDebounce"
          @clear="search_key = ''"
        >
          <template #label>
            <span @click="handshowCitylist">
              {{ city ? city : "" }}
              <van-icon name="arrow-down" />
            </span>
          </template>
          <template #action>
            <div @click="placeSearch">搜索</div>
          </template>
        </van-search>
      </div>
      <!--地图-->
      <div class="mapbox">
        <div id="container" class="map"></div>
        <div class="sign"></div>
      </div>
    </div>

    <div class="address-list">
      <div v-for="(item, index) in addressList" :key="index" class="address-item" @click="onSelectAddress(item)">
        <div class="mb-5">
          <van-icon class="c-999 mr-5" name="location" />
          <span class="name">{{ `${item.pname || ''} ${item.cityname}-${item.name}` }}</span>
        </div>
        <div class="text">
          {{ item.address }}
        </div>
        <!-- <van-button size="mini" type="danger" class="select" @click="onSelectAddress(item)">选择</van-button> -->
      </div>

      <van-empty v-if="addressList.length === 0" description="暂无数据，请输入地址进行查询" />
    </div>

    <van-action-sheet v-model:show="iscityShow" title="配送城市" style="height: 50%" get-container="#app">
      <van-search v-model="citySearch" placeholder="请输入搜索关键词" @update:model-value="selectCityList" />
      <van-radio-group v-model="city" class="city-list">
        <van-radio
          v-for="item in selfcity"
          :key="item.id"
          class="city-item"
          :name="item.deptName"
          :value="item.id"
          checked-color="#ff0000"
          @click="onSelectCity(item)"
        >{{ item.deptName }}</van-radio>
      </van-radio-group>
    </van-action-sheet>

    <van-dialog v-model:show="addressDialogVisible" title="请填写详细地址" :show-confirm-button="false">
      <van-form class="address-form" @submit="goOrder">
        <van-field
          readonly
          name="address"
          label=""
        >
          <template #input>
            <span>{{ `${addressObj.pname || ''} ${addressObj.cityname}-${addressObj.name}-${addressObj.address}` }}</span>
          </template>
        </van-field>
        <van-field
          type="textarea"
          rows="1"
          autosize
          required
          v-model="addressObj.detailAddress"
          name="detailAddress"
          label=""
          placeholder="填写详细地址，具体到楼层、门牌号"
          :rules="[{ required: true, message: '请填写详细地址' }]">
        </van-field>
        <div class="mg-10 d-f">
          <van-button class="mr-5" round block @click="addressDialogVisible = false">取 消</van-button>
          <van-button round block type="danger" native-type="submit">确 认</van-button>
        </div>
      </van-form>
    </van-dialog>
  </div>
</template>

<script>
import {
  getSelfDelivery // 获取城市列表
} from '@/api/common'
import { Toast } from 'vant'
import { inputTipThrottle } from '@/utils/map'
import { debounce } from 'lodash'

export default {
  name: 'OrderMap',
  data() {
    return {
      loading: false,
      city: '',
      search_key: '',
      selfcity: [],
      iscityShow: false,
      citySearch: '',
      addressList: [],
      addressDialogVisible: false,
      addressObj: {
        detailAddress: '',
      }
    }
  },
  created() {
  },
  mounted() {
    getSelfDelivery().then((res) => {
      this.selfcity = res.data
      this.originCityList = this.selfcity
    }).then(() => {
      // if (localStorage.getItem("city")) {
      //   this.city = localStorage.getItem("city");
      //   this.deptId = localStorage.getItem("deptId");
      // }
    })
    this.getCityInfo().then(() => {
      this.initMap()
      // this.placeSearch()
    })
  },
  methods: {
    // 初始化地图
    initMap(center) {
      // 初始化地图
      var map = (this._map = new AMap.Map('container', {
        zoom: 14, // 缩放级别
        center: center || this.center, // 设置地图中心点
        resizeEnable: true // 地图初始化加载定位到当前城市
      }))

      // 获取初始中心点并赋值
      var currentCenter = map.getCenter() // 此方法是获取当前地图的中心点
      this.center = [currentCenter.lng, currentCenter.lat] // 将获取到的中心点的纬度经度赋值给data的center
      // 创建标记
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(currentCenter.lng, currentCenter.lat) // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
      })
      // 将创建的点标记添加到已有的地图实例：
      map.add(this.marker)
    },

    selectCityList(value) {
      if (value) {
        this.selfcity = this.originCityList.filter(item => item.deptName.includes(value))
      } else {
        this.selfcity = this.originCityList || []
      }
    },
    placeSearch() {
      if (!this.search_key) {
        this.addressList = []
        return
      }
      this.loading = true
      // 关键字查询
      inputTipThrottle({
        city: this.city, // 兴趣点城市
        keyword: this.search_key || this.city
      }).then(addressList => {
        this.addressList = addressList || []
      }).finally(() => {
        this.loading = false
      })
    },

    onSelectCity(item) {
      // 配送范围
      this.deptId = item.id
      this.city = item.deptName
      localStorage.setItem('deptId', item.id)
      localStorage.setItem('city', item.deptName)
      this.iscityShow = false
      this.placeSearch()
    },
    handshowCitylist() {
      this.iscityShow = true
    },
    onKeyInput() {
      this.placeSearch()
    },
    onSelectAddress(item) {
      this.addressDialogVisible = true
      this.addressObj = {
        ...item,
        deptId: this.deptId,
        detailAddress: '',
      }
      this.onLocation(this.addressObj)
    },
    goOrder() {
      this.addressDialogVisible = false
      this.$EventBus.emit('selectAddress', this.addressObj)
      this.$router.push({
        path: '/order/edit',
        query: {
          ...this.$route.query,
          from: 'map'
        },
      })
    },
    onLocation(e) {
      this.marker.setPosition([e.location.lng, e.location.lat])
      this._map.setCenter([e.location.lng, e.location.lat])
    },
    // 获取用户所在城市信息
    getCityInfo() {
      return new Promise(resolve => {
        // 实例化城市查询类
        var citysearch = new AMap.CitySearch()
        // 自动获取用户IP，返回当前城市
        citysearch.getLocalCity((status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.city && result.bounds) {
              this.city = result.city
            }
          } else {
            Toast.fail(result.info)
          }
          resolve()
        })
      })
    }
  },
  created() {
    this.onKeyInputDebounce = debounce(this.onKeyInput, 500)
  }
}
</script>

<style lang="less" scoped>
.map-page {
  height: 100%;
  background: #f8f8f8;
  .head {
    position: sticky;
    top: 0px;
    z-index: 10;
    height: 300px;
  }
  .mapbox {
    width: 100%;
    height: 240px;
    background: #eceeee;

    .map {
      width: 100%;
      height: 240px;
    }
  }
}
.address-list {
  height: calc(100% - 300px);
  overflow: auto;
  .address-item {
    padding: 12px;
    padding-right: 50px;
    background-color: #fff;
    margin-top: 10px;
    font-size: 14px;
    position: relative;
    .name {
      font-weight: bold;
    }
    .text {
      color: #999;
      padding-left: 16px;
    }
    .select {
      position: absolute;
      top: 40%;
      right: 10px;
    }
  }
}
.city-list {
  padding: 0 12px;
  font-size: 14px;
  .city-item {
    line-height: 32px;
    height: 32px;
  }
}
.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
}

.address-form {

}
</style>
